package com.example.stag;

import org.jetbrains.annotations.NotNull;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/commodityRegistration")
public class CommodityRegistrationServlet extends HttpServlet {

    @Override
    public void init() {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
    }

    @Override
    protected void doGet(@NotNull HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        try {
            String id = req.getParameter("id");
            String name = req.getParameter("name");
            String batch = req.getParameter("batch");
            String dealer = req.getParameter("dealer");
            String description = req.getParameter("description");
            String suggestion = req.getParameter("suggestion");
            String circulationstatus = req.getParameter("circulationstatus");
            String salestatus = req.getParameter("salestatus");
            String openstatus = req.getParameter("openstatus");
            String productionTime = req.getParameter("productionTime");
            String productionAddress = req.getParameter("productionAddress");

            ResultSet resultSet = CommoditySQLOperation.searchById(id);
            PrintWriter writer = resp.getWriter();
            if (!resultSet.next()) {
                CommoditySQLOperation.insertCommodity(id, name, batch, dealer, description, suggestion, circulationstatus, salestatus, openstatus, productionTime, productionAddress, "");
                writer.println("OK");
            } else {
                writer.println("id existed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
